/**
 * 
 */
package com.thon.controller.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.SimpleTimeZone;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.thon.commons.utils.ImageUtil;
import com.thon.entity.user.Attachment;
import com.thon.entity.user.User;
import com.thon.service.user.AttachmentService;

/**
 * @author manpiaoyi
 * @email manpiaoyi@126.com
 * @date 2014-10-13
 * @description:
 */
@Controller
@RequestMapping("/common/attachment")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class AttachmentController {
	private static final Log log = LogFactory.getLog(AttachmentController.class);

	@Autowired
	private AttachmentService attachmentService;

	//移动端无水印文件上传
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<?> doUploadAction(
			@RequestParam(value = "uid") int userId,
			@RequestParam(value = "name") String name,
			@RequestParam(value = "mime") String mime,
			@RequestParam(value = "file") MultipartFile file) {

		Attachment attachment = new Attachment();
		attachment.setFileName(name);
		attachment = AttachmentUtil.parse(file, mime, userId);
		attachmentService.saveAttachment(attachment);
		AttachmentUtil.write(attachment,false);

		return new ResponseEntity(attachment, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/upload/multi", method = RequestMethod.POST)
	public ResponseEntity<?> doUploadAction(
			@RequestParam(value = "uid") int userId,
			@RequestParam(value = "press",defaultValue = "true") boolean press,
			MultipartHttpServletRequest request) {
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf;
		List<Attachment> attachments = new LinkedList<Attachment>();
		while (itr.hasNext()) {
			mpf = request.getFile(itr.next());
			Attachment attachment = AttachmentUtil.parse(mpf, mpf.getContentType(),  userId);
			attachmentService.saveAttachment(attachment);
			AttachmentUtil.write(attachment,press);
			attachments.add(attachment);
		}
		return new ResponseEntity(attachments, HttpStatus.CREATED);
	}
	
	@RequestMapping({ "/download/{targetId}" })
	public void doDownloadAction(@PathVariable Integer targetId, HttpServletResponse response)throws IOException {
		download(targetId, null, response);
	}

	@RequestMapping({ "/download/{targetId}/{dimension}" })
	public void doDownloadAction1(@PathVariable Integer targetId,
			@PathVariable String dimension, HttpServletResponse response)
			throws IOException {
		download(targetId, dimension, response);
	}

	public void download(Integer targetId, String dimension, HttpServletResponse response) {
		Attachment attachment = attachmentService.getAttachment(targetId);
		if (attachment == null) {
			attachment = new Attachment();
		}
		
		attachment.setDimension(dimension);
		AttachmentUtil.read(attachment);
		byte[] bytes = attachment.getBytes();
		
		response.setContentLength(bytes.length);
		response.setContentType(attachment.getContentType());
		if(!attachment.getContentType().matches("image/.*")&&!attachment.getContentType().matches("audio/.*")) {
			response.setHeader("Content-Disposition","attachment; filename=\"" + attachment.getFileName() +"\"");
		}
		
		// 添加Last-Modified和Cache-Control响应头信息
		SimpleDateFormat formatDate = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
		formatDate.setTimeZone(new SimpleTimeZone(0, "GMT"));
		response.addHeader("Last-Modified",formatDate.format(attachment.getCreatedDate()));
		response.addHeader("Cache-Control", "max-age=31536000");//最长缓存一年
		
		try {
			response.getOutputStream().write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
